// pages/hotel/detail/detail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hotel: null,
    loading: true,
    error: false,
    errorMsg: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.id) {
      this.setData({
        hotelId: options.id
      });
      this.loadHotel(options.id);
    } else {
      this.setData({
        loading: false,
        error: true,
        errorMsg: '酒店ID不存在'
      });
    }
  },

  /**
   * 加载酒店详情
   */
  loadHotel(hotelId) {
    this.setData({ loading: true, error: false });
    
    wx.mRequest({
      url: `/api/hotel/${hotelId}`,
      method: 'GET',
      success: (res) => {
        if (res.data) {
          this.setData({
            hotel: res.data,
            loading: false
          });
          
          // 设置页面标题
          if (res.data.name) {
            wx.setNavigationBarTitle({
              title: res.data.name
            });
          }
        } else {
          this.setData({
            loading: false,
            error: true,
            errorMsg: '未找到酒店信息'
          });
        }
      },
      fail: (err) => {
        console.error('获取酒店信息失败', err);
        this.setData({
          loading: false,
          error: true,
          errorMsg: '加载失败，请重试'
        });
      }
    });
  },
  
  /**
   * 预订房间
   */
  bookRoom(e) {
    const roomId = e.currentTarget.dataset.id;
    const room = this.data.hotel.rooms.find(item => item.id === roomId);
    
    if (!room || room.available <= 0) {
      wx.showToast({
        title: '该房型已满',
        icon: 'none'
      });
      return;
    }
    
    // 检查用户是否登录
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showModal({
        title: '提示',
        content: '预订房间需要先登录',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
      return;
    }
    
    // 跳转到预订页面
    wx.navigateTo({
      url: `/pages/order/hotel/hotel?roomId=${roomId}&hotelId=${this.data.hotelId}`
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    const hotelName = this.data.hotel ? this.data.hotel.name : '酒店详情';
    return {
      title: hotelName,
      path: `/pages/hotel/detail/detail?id=${this.data.hotelId}`
    };
  },
  
  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    if (this.data.hotelId) {
      this.loadHotel(this.data.hotelId);
    }
    wx.stopPullDownRefresh();
  }
})